<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8" />
        <title>12_案例练习-盒子来回移动</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }

            div {
                position: absolute;
                width: 100px;
                height: 100px;
                background-color: aqua;
            }
        </style>
    </head>
    <body>
        <div></div>

        <script>
            var div = document.querySelector('div');

             // 步长
             var step = 3;

            setInterval(function(){
                // 盒子的起始位置
                var startX = div.offsetLeft;

                // 盒子的结束位置
                var endX = startX + step;

                if(endX >= document.documentElement.clientWidth - div.clientWidth){
                    endX = document.documentElement.clientWidth - div.offsetWidth;
                    step = -3;
                }else if(endX <= 0){
                    endX = 0;
                    step = 3;
                }

                div.style.left = endX + 'px';

            },16);
        </script>
    </body>
</html>